package com.burgos.inventory;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Random;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;


public class UploadFile extends Activity implements OnClickListener {
	
	private String target;
	private Button shoot;
	private Button select;
	private Button change;
	private String barcode;
	private boolean takingpicture = false;
	private ProgressDialog pDialog;
	
	JSONParser jsonParser = new JSONParser();
	private static final String FILE_URL = "http://test1984.site11.com/Upload_Docs/uploadfile.php";
	
	protected ImageView _image;
	protected String _path = "";
	protected boolean _taken;
	protected static final String PHOTO_TAKEN = "photo_taken";
	private Random r;
	private String randomNum;
	private static final int FILE_SELECT_CODE = 0;
	private int serverResponseCode = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.upload_file);
		target = getIntent().getExtras().getString("keyword");
		barcode = getIntent().getExtras().getString("barcode");
		//CHOOSE to take pictre, select file and upload them
		shoot = (Button) findViewById(R.id.takephoto);
		shoot.setOnClickListener(this);
		select = (Button) findViewById(R.id.choosefile);
		select.setOnClickListener(this);
		change = (Button) findViewById(R.id.uploadNow);
		change.setOnClickListener(this);
		//generate a random number to name the image, after its ID
		r = new Random();
		randomNum = Integer.toString(r.nextInt(9990) + 10);
		_image = ( ImageView ) findViewById( R.id.imageTaken );
		//Variable to hold the path of the item that the user wants to upload
		_path = Environment.getExternalStorageDirectory() + "/images/" + target + "-" + randomNum + ".jpg";
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.takephoto:
			//decide to take a picture
			startCameraActivity();
			break;
		case R.id.choosefile:
			//open file explorer to select a file
			showFileChooser();
			break;
		case R.id.uploadNow:
			if(_path == ""){
				break;
			}
			//choose to upload item, a runnable
			pDialog = ProgressDialog.show(UploadFile.this, "", "Uploading file...", true);
            new Thread(new Runnable() {
                   public void run() {
                        runOnUiThread(new Runnable() {
                               public void run() {
                               }
                           });                      
                    uploadFile(_path);
                   }
                 }).start();
            
			break;
		default:
			break;
		}
	}
	
	//Method to start the camera and take picture
	protected void startCameraActivity()
	{
	    File file = new File( _path );
	    Uri outputFileUri = Uri.fromFile( file );
	    takingpicture = true;
	    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
	    intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
	    startActivityForResult( intent, 0 );
	}
	
	//Method executed after taking the picture of selecting file
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{	
	    Log.i( "MakeMachine", "resultCode: " + resultCode );
	    switch( resultCode )
	    {
	    	case 0:
	    		Log.i( "MakeMachine", "User cancelled" );
	    		break;
	    	case RESULT_OK:
	    		if(takingpicture)
	    		{
	    			onPhotoTaken();
	    			takingpicture = false;
	    			break;
	    		}
	    		if(requestCode == FILE_SELECT_CODE){
		    		Uri uri = data.getData();
				try {
					_path = getPath(this, uri);
				} catch (URISyntaxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		        break;
	    		}
	    	default:
	    		onPhotoTaken();
	    		break;
	    }
	}
	
	//Save image to SD
	protected void onPhotoTaken()
	{
	    _taken = true;
	    BitmapFactory.Options options = new BitmapFactory.Options();
	    options.inSampleSize = 4;	    	
	    Bitmap bitmap = BitmapFactory.decodeFile( _path, options );
	    _image.setImageBitmap(bitmap);
	}
	
	//To keep image on screen even if rotating the phone
	@Override
	protected void onSaveInstanceState( Bundle outState ) {
	    outState.putBoolean( UploadFile.PHOTO_TAKEN, _taken );
	}
	
	@Override 
	protected void onRestoreInstanceState( Bundle savedInstanceState)
	{
	    Log.i( "MakeMachine", "onRestoreInstanceState()");
	    if( savedInstanceState.getBoolean( UploadFile.PHOTO_TAKEN ) ) {
	    	onPhotoTaken();
	    }
	}

	//Method to upload file to a PHP server, taking the its path as a parameter
	protected void uploadFile(String sourceFileUri) {
      
        String fileName = sourceFileUri;
        HttpURLConnection conn = null;
        DataOutputStream dos = null;  
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024; 
        File sourceFile = new File(sourceFileUri); 
        if (!sourceFile.isFile()) {
         Log.e("uploadFile", "Source File Does not exist");
        }
            try { // open a URL connection to the Servlet
             FileInputStream fileInputStream = new FileInputStream(sourceFile);
             URL url = new URL(FILE_URL);
             conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
             conn.setDoInput(true); // Allow Inputs
             conn.setDoOutput(true); // Allow Outputs
             conn.setUseCaches(false); // Don't use a Cached Copy
             conn.setRequestMethod("POST");
             conn.setRequestProperty("Connection", "Keep-Alive");
             conn.setRequestProperty("ENCTYPE", "multipart/form-data");
             conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
             conn.setRequestProperty("uploaded_file", fileName); 
             dos = new DataOutputStream(conn.getOutputStream());
   
             dos.writeBytes(twoHyphens + boundary + lineEnd); 
             dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\"" + lineEnd);
             dos.writeBytes(lineEnd);
   
             bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size
   
             bufferSize = Math.min(bytesAvailable, maxBufferSize);
             buffer = new byte[bufferSize];
   
             // read file and write it into form...
             bytesRead = fileInputStream.read(buffer, 0, bufferSize);  
               
             while (bytesRead > 0) {
               dos.write(buffer, 0, bufferSize);
               bytesAvailable = fileInputStream.available();
               bufferSize = Math.min(bytesAvailable, maxBufferSize);
               bytesRead = fileInputStream.read(buffer, 0, bufferSize);               
              }
   
             // send multipart form data necesssary after file data...
             dos.writeBytes(lineEnd);
             /////
             //write more parameters other than the file
             dos.writeBytes(twoHyphens + boundary + lineEnd);
             //outputStream.writeBytes(twoHyphens + boundary + lineEnd); //less twohyphens
             dos.writeBytes("Content-Disposition: form-data; name=\"targetID\"" + lineEnd);
             //outputStream.writeBytes("Content-Length: " + invnum.length() + lineEnd);
             dos.writeBytes(lineEnd);
             dos.writeBytes(target + lineEnd);
             /////
             dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
   
             // Responses from the server (code and message)
             serverResponseCode = conn.getResponseCode();
             String serverResponseMessage = conn.getResponseMessage();
              
             Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
             if(serverResponseCode == 200){
                 runOnUiThread(new Runnable() {
                      public void run() {
                          Toast.makeText(UploadFile.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                      }
                  });                
             }    
             
             //close the streams //
             fileInputStream.close();
             dos.flush();
             dos.close();
              
        } catch (MalformedURLException ex) {  
            pDialog.dismiss();
            Toast.makeText(UploadFile.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
        } catch (Exception e) {
            pDialog.dismiss();  
            Log.e("Upload file to server", "error: " + e.getMessage(), e);
            Toast.makeText(UploadFile.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
            Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);  
        }
        pDialog.dismiss();
        Intent i = new Intent(UploadFile.this, Product.class);
		i.putExtra("keyword",barcode);
		finish();
		startActivity(i);
       }

	//Method to choose a file using the phone's file explorer
	private void showFileChooser() {
	    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
	    intent.setType("*/*"); 
	    intent.addCategory(Intent.CATEGORY_OPENABLE);
	    try {
	        startActivityForResult(
	                Intent.createChooser(intent, "Select a File to Upload"),
	                FILE_SELECT_CODE);
	    } catch (android.content.ActivityNotFoundException ex) {
	        // Potentially direct the user to the Market with a Dialog
	        Toast.makeText(this, "Please install a File Manager.", 
	                Toast.LENGTH_SHORT).show();
	    }
	}
	
	//Method to get the path of the chosen file
	public static String getPath(Context context, Uri uri) throws URISyntaxException {
	    if ("content".equalsIgnoreCase(uri.getScheme())) {
	        String[] projection = { "_data" };
	        Cursor cursor = null;
	        try {
	            cursor = context.getContentResolver().query(uri, projection, null, null, null);
	            int column_index = cursor.getColumnIndexOrThrow("_data");
	            if (cursor.moveToFirst()) {
	                return cursor.getString(column_index);
	            }
	        } catch (Exception e) {
	            // Eat it
	        }
	    }
	    else if ("file".equalsIgnoreCase(uri.getScheme())) {
	        return uri.getPath();
	    }
	    return null;
	} 
}


